package com.sinopec.uhf.chengwei

import android.app.Activity
import android.content.Context
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.rscja.deviceapi.RFIDWithUHFA8
import com.sinopec.iuhf.IUhfHelper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.launch

//通过协程来读取 关闭协程 则读取就关闭
class LifecycleUhfHelper(private val context: Context) : LifecycleEventObserver, IUhfHelper {

    private val reader by lazy {
        RFIDWithUHFA8.getInstance().also {

//            it.setFilter(RFIDWithUHFA8.Bank_EPC, 0, 0, "")
//           it.setFilter(RFIDWithUHFA8.Bank_TID, 0, 0, "")
//           it.setFilter(RFIDWithUHFA8.Bank_USER, 2, 3, "")
        }
    }

    //开始读取
    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        when (event) {
            Lifecycle.Event.ON_CREATE -> {
                source.lifecycleScope.launch {
                    reader.init(context)
                }
            }

            Lifecycle.Event.ON_DESTROY -> {
                reader.free()
            }

            else -> {

            }
        }
    }

    override fun readTags(userOrEpc: (user: String, epc: String) -> String): Flow<String> {
        return CoroutineRead.readATag(reader)
            .map {
                if (it == null) {
                    ""
                } else {
                    Log.d("成为主机模式", "readATag: \nepc=${it.epc}\nuser=${it.user}\ntid=${it.tid}rssi=${it.rssi}")
                    userOrEpc(it.user ?: "", it.epc ?: "")
                }
            }.onCompletion {
                reader.stopInventory()
            }.flowOn(Dispatchers.IO)
    }

}

//从生命周期中获取 uhf控制器 它会自动跟随生命周期的变化向uhf内核发送指令
val LifecycleOwner.lifecycleUhfHelper: LifecycleUhfHelper
    get() {
        val helper = LifecycleUhfHelper(
            when {
                this is Activity -> this
                else -> error("此处无法获取 上下文 context")
            }
        )
        lifecycle.addObserver(helper)
        return helper
    }